/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Company;
import cn.net.ecode.modules.sys.entity.Office;
import cn.net.ecode.modules.sys.service.OfficeService;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 机构Controller
 * @author ThinkGem
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office")
public class OfficeController extends BaseController {

	@Autowired
	private OfficeService officeService;
	@Autowired
	private UserController userController;

	@ModelAttribute
	public Office get(String officeCode, boolean isNewRecord) {
		return officeService.get(officeCode, isNewRecord);
	}

	//	@RequiresPermissions("sys:office:view")
	//	@RequestMapping(value = {""})
	//	public String index(Office office, Model model) {
	////        model.addAttribute("list", officeService.findAll());
	//		return "modules/sys/officeIndex";
	//	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = {"list", ""})
	public String list(Office office, Model model) {
		office.setStatus(StringUtils.EMPTY);
		model.addAttribute("office", office);
		return "modules/sys/officeList";
	}

	@RequiresPermissions("sys:office:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public List<Office> listData(Office office) {
		if (StringUtils.isBlank(office.getParentCode())){
			office.setParentCode(Office.ROOT_CODE);
		}
		if (Office.ROOT_CODE.equals(office.getParentCode())
				&&(StringUtils.isNotBlank(office.getOfficeCode())
				|| StringUtils.isNotBlank(office.getOfficeName())
				|| StringUtils.isNotBlank(office.getFullName())
				|| StringUtils.isNotBlank(office.getCompany() == null 
					? null : office.getCompany().getCompanyCode()))){
			office.setParentCode(null);
		}else{
			office.setOfficeCode(null);
			office.setOfficeName(null);
			office.setFullName(null);
			office.setCompany(null);
		}
		List<Office> list = officeService.findList(office);
		return list;
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "form")
	public String form(Office office, Model model) {
		if (office.getParent() != null && StringUtils.isNotBlank(office.getParent().getOfficeCode())) {
			office.setParent(officeService.get(office.getParent().getOfficeCode()));
		}
		// 自动获取排序号
		if (StringUtils.isBlank(office.getOfficeCode()) && office.getParent() != null) {
			int size = 0;
			List<Office> list = officeService.findList(false);
			for (int i = 0; i < list.size(); i++) {
				Office e = list.get(i);
				if (e.getParent() != null && e.getParent().getOfficeCode() != null
						&& e.getParent().getOfficeCode().equals(office.getParent().getOfficeCode())) {
					size++;
				}
			}
			office.setOfficeCode(office.getParent().getOfficeCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size + 1 : 1), 3, "0"));
			office.setIsNewRecord(true);
		}
		model.addAttribute("office", office);
		return "modules/sys/officeForm";
	}

	@RequiresPermissions("sys:office:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Office office, String cmd, Model model, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		StringBuilder builder = new StringBuilder();
		if (!beanValidator(builder, office)) {
			return renderResult(Global.FALSE, builder.toString());
		}
		officeService.save(office);

//		if(office.getChildDeptList()!=null){
//			Office childOffice = null;
//			for(String officeCode : office.getChildDeptList()){
//				childOffice = new Office();
//				childOffice.setName(DictUtils.getDictLabel(officeCode, "sys_office_common", "未知"));
//				childOffice.setParent(office);
//				childOffice.setArea(office.getArea());
//				childOffice.setType("2");
//				childOffice.setGrade(String.valueOf(Integer.valueOf(office.getGrade())+1));
//				childOffice.setUseable(Global.YES);
//				officeService.save(childOffice);
//			}
//		}

		return renderResult(Global.TRUE, "保存机构'" + office.getOfficeName() + "'成功");
	}

//	@RequiresPermissions("sys:office:edit")
//	@ResponseBody
//	@RequestMapping(value = "delete")
//	public String delete(Office office, RedirectAttributes redirectAttributes) {
//		if(Global.isDemoMode()){
//			return renderResult(Global.FALSE, "演示模式，不允许操作！");
//		}
////		if (Office.isRoot(officeCode)){
////			addMessage(redirectAttributes, "删除机构失败, 不允许删除顶级机构或编号空");
////		}else{
//			officeService.delete(office);
////			addMessage(redirectAttributes, "删除机构成功");
////		}
//		return renderResult(Global.TRUE, "删除机构"+office.getOfficeName()+"成功");
//	}

	@RequiresPermissions("sys:office:disable")
	@ResponseBody
	@RequestMapping(value = "disable")
	public String disable(Office office, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		List<Office> officeList = officeService.getEnabledList(office);
		if (officeList != null && officeList.size() > 0) {
			return renderResult(Global.FALSE, "机构" + office.getOfficeName() + "包含未停用的机构，请先停用子节点！");
		}
		officeService.disable(office);
		return renderResult(Global.TRUE, "停用机构" + office.getOfficeName() + "成功");
	}

	@RequiresPermissions("sys:office:disable")
	@ResponseBody
	@RequestMapping(value = "disableByGroup")
	public String disableByGroup(Office office, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		officeService.disableByGroup(office);
		return renderResult(Global.TRUE, "停用机构" + office.getOfficeName() + "及子机构成功");
	}

	@RequiresPermissions("sys:office:enable")
	@ResponseBody
	@RequestMapping(value = "enable")
	public String enable(Office office, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		officeService.enable(office);
		return renderResult(Global.TRUE, "启用机构" + office.getOfficeName() + "成功");
	}

	@RequiresPermissions("sys:office:enable")
	@ResponseBody
	@RequestMapping(value = "enableByGroup")
	public String enableByGroup(Office office, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		officeService.enableByGroup(office);
		return renderResult(Global.TRUE, "启用机构" + office.getOfficeName() + "及子机构成功");
	}

	/**
	 * 获取机构JSON数据。
	 * @param extCode 排除的ID
	 * @param parentCode 上级Code
	 * @param isAll 是否显示所有机构（true：不进行权限过滤）
	 * @param type	类型（1：公司；2：部门/小组/其它：3：异步用户(抛弃方法)；4：一次性加载用户(推荐方法)）
	 * @param companyCode 仅查询公司下的机构
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @param isShowFullName 是否显示全机构名称
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String extCode, String parentCode, Boolean isAll,
			String type, String companyCode, String isShowCode, String isShowFullName) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list;
		if (StringUtils.isNotBlank(companyCode)) {
			if (isAll != null && isAll){
				list = officeService.findAllList(new Office(new Company(companyCode)));
			}else{
				list = officeService.findList(new Office(new Company(companyCode)));
			}
		}else{
			list = officeService.findList(isAll);
		}
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			if ((StringUtils.isBlank(extCode) || (extCode != null && !extCode.equals(e.getOfficeCode()) && !e.getParentCodes().contains("," + extCode + ",")))
					&& (StringUtils.isBlank(parentCode) || (parentCode != null && (parentCode.equals(e.getOfficeCode()) || e.getParentCodes().contains("," + parentCode + ","))))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
					&& (e.getStatus().equals(Company.STATUS_NORMAL))) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getOfficeCode());
				map.put("pId", e.getParentCode());
				map.put("pIds", e.getParentCodes());
				String name = e.getOfficeName();
				if ("true".equals(isShowFullName) || "1".equals(isShowFullName)){
					name = e.getFullName();
				}
				if ("true".equals(isShowCode) || "1".equals(isShowCode)){
					map.put("name", "(" + e.getViewCode() + ")" + name);
				}else if ("2".equals(isShowCode)){
					map.put("name", name + "(" + e.getViewCode() + ")");
				}else{
					map.put("name", name);
				}
				// 一次性客户端，异步加载用户(抛弃方法)
				if (type != null && "3".equals(type)) {
					map.put("isParent", true);
				}
				// 一次性后台加载用户，提高性能(推荐方法)
				if (type != null && "4".equals(type)) {
					map.put("isParent", true);
					List<Map<String, Object>> userList;
					userList = userController.treeData(e.getOfficeCode(), isAll, isShowCode);
					mapList.addAll(userList);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}

//	/** 
//	 * 判断列表中是否包含该officeCode
//	 * @author jiangwenchao
//	 * @param list
//	 * @param officeCode
//	 * @return boolean  
//	 */
//	private boolean isExist(List<Office> list, String officeCode) {
//		if (list == null || officeCode == null || officeCode.equals("")) {
//			return false;
//		}
//		for (Office o : list) {
//			if (StringUtils.isNotBlank(o.getOfficeCode()) && officeCode.equals(o.getOfficeCode())) {
//				return true;
//			}
//		}
//		return false;
//	}

	@RequiresPermissions("sys:office:edit")
	@ResponseBody
	@RequestMapping(value = "dataFix")
	public String dataFix() {
		officeService.updateFixParentCodes();
		return renderResult(Global.TRUE, "数据修复成功");
	}
}
